/**
 * 
 */
package org.swing.utility.common.stream;

import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import org.swing.utility.common.exception.SAMException;
import org.swing.utility.common.file.IOUtil;

/**
 * @author lqnhu
 *
 */
public class TempStreamFactory {
	private static SnappyLoader snappyLoader = null;

	private static synchronized SnappyLoader getSnappyLoader() {
		if (snappyLoader == null)
			snappyLoader = new SnappyLoader();
		return snappyLoader;
	}

	/**
	 * Wrap the given InputStream in a SnappyInputStream if available.
	 * 
	 * @return If Snappy is available, a SnappyInputStream wrapping inputStream.
	 *         If not, and bufferSize > 0, a BufferedInputStream. Otherwise
	 *         inputStream is returned.
	 */
	public InputStream wrapTempInputStream(final InputStream inputStream,
			final int bufferSize) {
		InputStream is = IOUtil.maybeBufferInputStream(inputStream, bufferSize);
		if (getSnappyLoader().SnappyAvailable) {
			try {
				return getSnappyLoader().wrapInputStream(is);
			} catch (Exception e) {
				throw new SAMException("Error creating SnappyInputStream", e);
			}
		} else {
			return is;
		}
	}

	/**
	 * Wrap the given OutputStream in a SnappyOutputStream if available.
	 * 
	 * @return If Snappy is available, a SnappyOutputStream wrapping
	 *         outputStream. If not, and bufferSize > 0, a BufferedOutputStream.
	 *         Otherwise outputStream is returned.
	 */
	public OutputStream wrapTempOutputStream(final OutputStream outputStream,
			final int bufferSize) {
		OutputStream os = outputStream;
		if (bufferSize > 0)
			os = new BufferedOutputStream(os, bufferSize);
		if (getSnappyLoader().SnappyAvailable) {
			try {
				os = getSnappyLoader().wrapOutputStream(os);
			} catch (Exception e) {
				throw new SAMException("Error creating SnappyOutputStream", e);
			}
		}
		return os;
	}
}
